﻿/*
 * Twipler - Twitter Web Client with features.
 *  
 *  Copyright (C) 2010. Ian Quigley
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details. 
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>. 
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Dimebrain.TweetSharp.Model;
using log4net;
using log4net.Config;
using log4net.Core;
using log4net.Util;
using Twipler.Data.Entity.Twipler;
using Twipler.Twitter;
using Twipler.Xtensions;
using Twipler.Data.Cache;
using System.Web.Caching;

namespace Twipler.App.Session
{
	public class InnerSession : IInnerSession
	{
		private List<ISessionCleanup> _cleanupList;

        private Visitor _visitor = null;
		public Visitor Visitor { get { return _visitor ?? new VisitorAnon() ; } set { _visitor = value; }}
		public string IP { get; set; }
		public DateTime LastSeen { get { return _lastSeen;}  }
		public string LastPage { get { return _lastPage; } }
		public string SessionId { get { return _sessionId; } }
        
		private DateTime _lastSeen ;
		private string _lastPage;

		internal InnerSession(string sessionId)
		{
			_sessionId = sessionId;
			_cleanupList = new List<ISessionCleanup>();
			IP = HttpContext.Current.Request.UserHostAddress;
			_lastPage = HttpContext.Current.Request.RawUrl;
			_lastSeen = DateTime.Now;
		}

		internal string _sessionId;

		public override string ToString()
		{
			return "SessionTrack[ " + Visitor == null ? "<anonymous>" : Visitor.ScreenName + "]";
		}
        
		public void AddToCleanUp(ISessionCleanup item)
		{
			ILogExtension.InMethod(Current.Log, "SessionTrack.AddToCleanup [" + item.ToString() + "]");

			lock (typeof(InnerSession))
				_cleanupList.Add(item);            
		}

		public void RemoveFromCleanUp(ISessionCleanup item)
		{
			ILogExtension.InMethod(Current.Log, "SessionTrack.AddToCleanup [" + item.ToString() + "]");

			lock (typeof(InnerSession))
				_cleanupList.Remove(item);            
		}

		public void CleanUp()
		{
			ILogExtension.InMethod(Current.Log, "SessionTrack.CleanUp [" + _sessionId + ", count: " + _cleanupList.Count() + "]");

			foreach (ISessionCleanup cleaner in _cleanupList)
				cleaner.SessionEnd();
		}

		public void ViewingPage(string page)
		{
			_lastPage = page;
			_lastSeen = DateTime.Now;
		}


		private Caller _apiCaller = null;
		/// <summary>
		/// Get the Twitter Api Caller
		/// </summary>
		public Caller ApiCaller
		{
			get
			{
				if (_apiCaller == null)
					_apiCaller = new Caller();
                
				return _apiCaller;
			}
		}

		public OAuthToken OAuthToken { get; set; }
		public string[] Credentials { get; set; }

        private List<string> _screenNames = null;
        public List<string> ScreenNames
        {
            get 
            {
                List<string> names = (List<string>)HttpContext.Current.Cache.Get("ScreenNames_" + Visitor.Id);
                if (names != null)
                    return names;

                names = GetNames(Visitor.Id);
                HttpContext.Current.Cache.Add("ScreenNames_" + Visitor.Id, names, null, DateTime.Now.AddSeconds(60), Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Low, null);
      
                return names;
            }
			set
			{
				_screenNames = value;
			}
        }

        private List<string> GetNames(int twitterId)
        {
            List<string> names = new List<string>();

            using (TableStore<Follower> followers = TableStore<Follower>.Open(twitterId))
            using (TableStore<TwitterUserDetails> details = TableStore<TwitterUserDetails>.Open())
            {
                foreach (Follower follower in followers.ReadAll())
                {
                    TwitterUserDetails detail = details.Find(follower.Id);
                    if (detail != null)
                        names.Add(detail.ScreenName);
                }
            }
            return names;
        }

    }
}